/* eslint-disable no-unused-vars */

import api from '@/api'

import moduleCreator from '../moduleCreator'

const modelName = 'survey.user_input'
const Model = api.env(modelName)

const browse_question = async id => {
  const fields = {
    survey_id: {
      question_ids: {
        question: null,
        question_type: null,
        labels_ids: { value: null },
        labels_ids_2: { value: null },
        matrix_subtype: null
      }
    },

    user_input_line_ids: {
      question_id: null,
      value_text: null,
      value_number: null,
      value_date: null,
      value_datetime: null,
      value_free_text: null,
      value_suggested: null
    }
  }

  const question_type_to_answer_type_map = {
    free_text: 'free_text',
    textbox: 'text',
    numerical_box: 'number',
    date: 'date',
    datetime: 'datetime',
    simple_choice: 'suggestion',
    multiple_choice: 'suggestion',
    matrix: 'suggestion'
  }

  const res = await Model.browse_one(id, { fields })
  console.log('input,', res)
  const question_ids = res.survey_id__object.question_ids__objects || []
  const user_input_lines = res.user_input_line_ids__objects || []
  console.log('input 2lines,', user_input_lines)

  const questions = question_ids
    .filter(item => item.question_type !== 'matrix')
    .map(item => {
      const answer_type = question_type_to_answer_type_map[item.question_type]
      const newItem = {
        id: item.id,
        user_input_id: res.id,
        question_id: item.id,
        question: item.question,
        question_type: item.question_type,
        answer_type,

        value: {
          value_text: undefined,
          value_number: undefined,
          value_date: undefined,
          value_datetime: undefined,
          value_free_text: undefined,
          value_suggested: undefined
        }
      }

      const selects = ['simple_choice', 'multiple_choice', 'matrix']
      if (selects.includes(item.question_type)) {
        newItem.labels = item.labels_ids__objects.map(lab => {
          return { id: lab.id, text: lab.value, value: lab.id }
        })
      }

      if (item.question_type === 'matrix') {
        newItem.labels2 = item.labels_ids_2__objects.map(lab => {
          return { id: lab.id, text: lab.value, value: lab.id }
        })
        newItem.matrix_subtype = item.matrix_subtype
      }

      const lns = user_input_lines.filter(ln => ln.question_id === item.id)
      // console.log('lns,', item, lns)

      if (item.question_type === 'matrix') {
        // do nothiog
      } else if (item.question_type === 'multiple_choice') {
        newItem.value.value_suggested = lns.map(it => it.value_suggested)
        newItem.value.value_suggested__name = lns
          .map(it => it.value_suggested__name)
          .join(',')

        newItem.value.display_name = newItem.value.value_suggested__name
      } else if (item.question_type === 'simple_choice') {
        const ln = lns.length ? lns[0] : {}
        newItem.value.value_suggested = ln.value_suggested
        newItem.value.value_suggested__name = ln.value_suggested__name
        newItem.value.display_name = newItem.value.value_suggested__name
      } else {
        const value_field = `value_${answer_type}`
        const ln = lns.length ? lns[0] : {}
        newItem.value[value_field] = ln[value_field]
        newItem.value.display_name = newItem.value[value_field]
      }

      return newItem
    })

  return {
    ...res,
    questions
  }
}

const write_question = async(id, questions, user_input_lines) => {
  //
  console.log('write_question', id, questions, user_input_lines)

  const lines = questions.reduce((acc, item) => {
    // console.log('cur,', item)

    if (item.question_type === 'matrix') {
      // do nothiog
      return acc
    }

    const lns = user_input_lines.filter(ln => ln.question_id === item.id)
    // console.log('lns,', item, lns)

    const single = [
      'free_text',
      'textbox',
      'numerical_box',
      'date',
      'datetime',
      'simple_choice'
    ]

    if (item.question_type === 'multiple_choice') {
      item.value.value_suggested.forEach((element, index) => {
        const vals = {
          answer_type: item.answer_type,
          question_id: item.question_id
        }
        vals.value_suggested = element
        const op = lns.length > index ? [1, lns[index].id] : [0, 0]
        acc.push([...op, vals])
      })
      lns.forEach((element, index) => {
        if (index >= item.value.value_suggested.length) {
          acc.push([2, element.id, 0])
        }
      })
    } else if (single.includes(item.question_type)) {
      const vals = {
        answer_type: item.answer_type,
        question_id: item.question_id
      }
      const value_field = `value_${
        item.answer_type === 'suggestion' ? 'suggested' : item.answer_type
      }`

      vals[value_field] = item.value[value_field]
      const ln = lns.length ? lns[0] : {}
      const op = ln.id ? [1, ln.id] : [0, 0]
      acc.push([...op, vals])
    }

    return acc
  }, [])

  const values = { id, user_input_line_ids: lines }
  console.log('values', values)

  return await Model.write(values)
}

const state = {
  //
}

const mutations = {
  //
}

const actions = {
  async search({ commit, state, dispatch }, payload) {
    return dispatch('_search', payload)
  },

  async browse_question({ commit, state, dispatch }, payload) {
    const { id } = payload
    const res = await browse_question(id)
    commit('SET_DataDict', res)
    return new Promise(resolve => {
      resolve(res)
    })
  },

  async write_question({ commit, state, dispatch }, payload) {
    const { id, questions, user_input_line_ids__objects } = payload
    // console.log('write_question', payload)
    const res = await write_question(
      id,
      questions,
      user_input_line_ids__objects
    )
    console.log('write_question ok', res)
    // TBD ? return ?
  }
}

export default moduleCreator(modelName, {
  namespaced: true,
  state,
  mutations,
  actions
})
